package com.crazyread.imple;

import com.crazyread.dao.UserAuthorityMapper;
import com.crazyread.dao.UserMapper;
import com.crazyread.model.domain.Authority;
import com.crazyread.model.domain.User;
import com.crazyread.model.domain.UserAuthority;
import com.crazyread.security.AccountUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserAuthorityMapper userAuthorityMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selUserByUsername(username);
        if (user == null){
            throw new UsernameNotFoundException("用户或密码不正确");
        }
        return new AccountUser(user.getId(), user.getUsername(), user.getPassword(), getUserAuthority(user.getId()));
    }

    /**
     * 获取用户权限信息（角色、菜单权限）
     * @param userId
     * @return
     */
    public List<GrantedAuthority> getUserAuthority(Long userId){

        // 角色(ROLE_admin)、菜单操作权限 sys:user:list
        UserAuthority userAuthority = userAuthorityMapper.getUserAuthority(userId);

        Authority authority = userMapper.selAuthorityById(userAuthority.getAuthorityId());  // ROLE_admin,ROLE_normal,sys:user:list,....

        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority.getAuthority());


    }
}
